#include <iostream>
#include <string>
#include <cstring>
#include <cstdlib>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include "Log.hpp"

void Usage(char *argv[])
{
    std::cout << "Usage:\n\t" << argv[0] << " serverip serverport\n"
              << std::endl;
}

// 传输命令
int main(int argc, char *argv[])
{
    // 使用手册
    if (argc != 3)
    {
        Usage(argv);
        exit(1);
    }

    // 先拿到服务器ip再是端口号
    std::string serverip = argv[1];
    // 将字符串形式的端口号转换为整数
    uint16_t serverport = std::stoi(argv[2]);

    // 1 创建socket
    // AF_INET:ipv4(网络通信)
    // SOCK_DGRAM:udp
    int sockfd = socket(AF_INET, SOCK_DGRAM, 0);
    if (sockfd < 0)
    {
        LOG(ERROR, "socket error");
        exit(2);
    }

    LOG(INFO, "socket success");

    // 构建目标主机socket信息
    struct sockaddr_in server;

    bzero(&server, sizeof(server));
    server.sin_family = AF_INET;
    server.sin_port = htons(serverport);
    server.sin_addr.s_addr = inet_addr(serverip.c_str());

    std::string message;

    while (true)
    {
        std::cout << "请输入要发送的消息:";
        std::getline(std::cin, message);
        sendto(sockfd, message.c_str(), message.size(), 0, (struct sockaddr *)&server, sizeof(server));

        struct sockaddr_in perror;
        socklen_t len = sizeof(perror);
        char buf[1024];
        ssize_t ret = recvfrom(sockfd, buf, sizeof(buf) - 1, 0, (struct sockaddr *)&perror, &len);

        if (ret > 0)
        {
            buf[ret] = 0;
            std::cout << "server echo:" << buf << std::endl;
        }
    }

    return 0;
}